<template>
	<Layout>
		<view class="bonus-page">
				<div class="select_month_box">
					<UniSelect v-model="dateStr" style="width: 300rpx;" @change="deteChange" :options="monthOptions" />
				</div>
		    <!-- 顶部金额 -->
		    <view class="total_amount">
		      <text class="amount">$ {{ formatMoney(detailObj.totalBonus)}}</text>
		      <text class="label">獎金總額</text>
		      <button class="confirm_btn" :class="statClassMap[detailObj.state]">{{ stateMap[detailObj.state] }}</button>
		    </view>
		
		    <!-- 表格数据展示 -->
		    <view class="bonus_table">
					<view class="row">
						<div class="col left_col">
							<text>期數</text>
						</div>
						<div class="col right_col">
							<text>{{ detailObj.performanceDate&&detailObj.performanceDate.slice(0,7) }}</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>獎金池</text>
						</div>
						<div class="col right_col">
							<text class="active_num">${{ formatMoney(detailObj.bonusPool) }}</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>業績/目標</text>
						</div>
						<div class="col right_col">
							<text>{{ formatMoney(detailObj.actualProfit) }} / {{ formatMoney(detailObj.profitTarget) }}</text>
							<text v-if="!isTargetReached"> ( {{completionRate}} %  <span class="chart red_char">未達成</span>)</text>
							<text v-if="isTargetReached"> (  <span class="chart green_char">已達成</span>)</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>其他</text>
						</div>
						<div class="col right_col">
							<text>${{ formatMoney(detailObj.otherMoney) }}</text>
							<text class="info_char">{{ detailObj.otherRemark }}</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>積分提成比</text>
						</div>
						<div class="col right_col">
							<text>{{ formatDiscount(detailObj.commissionRatio) }} %</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>獎金級距</text>
						</div>
						<div class="col right_col">
							<text>{{formatDiscount(detailObj.levelDistanceValue) }}%</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>獎金總額</text>
						</div>
						<div class="col right_col">
							<text class="active_box">{{ formatMoney(detailObj.totalBonus) }} (USD)</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>匯率</text>
						</div>
						<div class="col right_col">
							<text>{{ detailObj.exchangeRate }}</text>
						</div>
					</view>

					<view class="row">
						<div class="col left_col">
							<text>貨幣換算</text>
						</div>
						<div class="col right_col">
							<text class="active_box">{{ formatMoney(detailObj.conversionBonus) }} ({{ detailObj.currencySymbol || '$' }})</text>
						</div>
					</view>

		    </view>

				<!-- 記錄顯示 -->
				<view class="chat_section">
					<view class="chat_item" v-for="(item, index) in chatList" :key="index">
						<view class="avatar_box">
								<text class="avatar_name">{{ item.upperCaseName }}</text>
						</view>
						<view class="message_box">
							<view class="message_header">
								<text class="message_name">{{ item.actionUser }}</text>
								<text class="message_time">{{ item.createTime }}</text>
							</view>
							<view class="message-content" v-if="item.content.length || item.ossUrl">
								<text>{{ item.content }}</text>
								<div v-if="item.ossUrl" class="down_btn_box" mode="link"@click="handleDown(item.ossUrl)" >下載附件</div>
							</view>
						</view>
					</view>

					<!-- 底部按钮 -->
					<view class="chat-footer" v-show="disableBtn  && detailObj.state == 10">
						<button class="btn confirm-btn" @click="handleConfirm">確認金額</button>
						<button class="btn confirm-btn" @click="goNewPage">我對金額有異議</button>
					</view>
				</view>
		  </view>
	</Layout>
</template>

<script>
import UniSelect from '@/components/UniSelect/index.vue';
import { formatMoney, formatDiscount } from '@/utils/format.js'
import { getMyBonus, confirmBonus} from '@/api/salesaman.js'
export default {
  components: { UniSelect },
		data() {
			return {
				dateStr: this.getCurrentMonth(),
				monthOptions : [],
				stateMap: {
					0: '待審核',
					1: 'CEO已確認',
					10: '人資審核通過',
					11: '業務員確認',
					12: '主管確認',
					4: '有異議'
				},
				statClassMap: {
					0: 'status_pending', // #f9ba23 橘黃
					1: 'status_ceo', // #33cc33 綠色
					10: 'status_hr', // #66ccff 天藍
					11: 'status_sales', // #ff9900 深橙
					12: 'status_manager', // #9966cc 紫色
					4: 'status_danger' // #f92a23 紅色
				},
				detailObj: {},
				chatList: []
			};
		},
		computed: {
			isTargetReached() {
				return (this.detailObj.actualProfit || 0) >= (this.detailObj.profitTarget || 0)
			},
			completionRate() {
				const target = this.detailObj.profitTarget || 0
				const actual = this.detailObj.actualProfit || 0
				if (!target) return '0.00'
				return ((actual / target) * 100).toFixed(2)
			},
			disableBtn(){
				return Object.keys(this.detailObj).length
			}
		},
		onLoad(options) {
			this.routeQuery = options;
			if(this.routeQuery.dateStr){
				this.dateStr = this.routeQuery.dateStr
			}
			this.getDetailData()
		},
		created() {
			this.monthOptions = this.generateMonthOptions(2010)
		},
		methods: {
			formatMoney,
			formatDiscount,
			getDetailData(){
			uni.showLoading({title: '數據加載中...', mask: true })
				this.chatList  = []
				this.detailObj = {}
				getMyBonus({
					dateStr: this.dateStr
				}).then(res => {
					const currentUserId = this.$store.getters.userInfo.id
					this.detailObj  = res.data.myBonus
					if(res.data.logs.length){
						this.chatList = res.data.logs.map( item=>{
							return{
								...item,
								actionUser: item.createUser === currentUserId ? '我' : item.operationUserName,
								upperCaseName: this.get_initials(item.operationUserName)
							}
						})
					}
					uni.hideLoading();
				})
			},	
			isChinese(str){
				return /^[\u4e00-\u9fa5]+$/.test(str)
			},	
			// 获取名字首字母并转成大写
			get_initials(name) {
				if(!name) return ''
				// 如果是汉字返回第一个
				if(this.isChinese(name)) return name.charAt(0)
				const initials = name.match(/\b\w/g) || []
				return ((initials.shift() || '') + (initials.pop() || '')).toUpperCase()
			},
			handleConfirm(){
				confirmBonus({id: this.detailObj.id}).then(res=>{
					uni.showToast({
            title: res.message,
            icon: 'none'
          })
					this.getDetailData()
				})
			},
			goNewPage(){
				/**
				 * uni.redirectTo({
					url: '/pages/salesman/bonusDissent/index?dateStr=' +this.dateStr})
				 */
				this.$u.route({
					url: '/pages/salesman/bonusDissent/index',
					params: {
						dateStr: this.dateStr
					}
				})
			},
			deteChange(){
				this.getDetailData()
			},
			getCurrentMonth() {
				const now = new Date()
				const year = now.getFullYear()
				const month = now.getMonth() 
				return `${year}-${month < 10 ? '0' + month : month}`
			},
			generateMonthOptions(startYear) {
				const options = []
				const now = new Date()
				const currentYear = now.getFullYear()
				const currentMonth = now.getMonth() + 1

				for (let year = startYear; year <= currentYear; year++) {
					const maxMonth = year === currentYear ? currentMonth : 12
					for (let month = 1; month <= maxMonth; month++) {
						const m = month < 10 ? `0${month}` : `${month}`
						options.push({
							label: `${year}-${m}`,
							value: `${year}-${m}`,
						})
					}
				}
				return options.reverse()
			},
			handleDown(urls){
				const arr = urls.split(',')
				if (!arr.length) {
					uni.showToast({ title: '無效的文件地址', icon: 'none' });
					return;
				}
				uni.showLoading({ title: '下載中...', mask: true });
				arr.forEach(item=>{
					this.downloadForH5(item)
				})
				uni.hideLoading();
			},
			downloadForH5(url) {
				const link = document.createElement('a')
				link.href = url
				link.download = url.split('/').pop() // 使用 URL 最后一部分作为文件名
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
			}
		},
	}
</script>

<style lang="scss" scoped>
.bonus-page {
  padding: 30rpx;
	padding-bottom: 50px;
  background-color: #f9f9f9;
  font-family: 'Helvetica Neue', sans-serif;
	.select_month_box{
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 60rpx 0;
		margin-bottom: 40rpx;
	}
	.total_amount {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 14rpx;
		margin-bottom: 50rpx;
		.amount {
			font-size: 60rpx;
			font-weight: bold;
			color: #2e7d32;
		}
		.confirm_btn {
			width: 220rpx;
			margin-top: 20rpx;
			padding: 0rpx 30rpx;
			/* background-color: #f2a50a; */
			color: #fff;
			border-radius: 10rpx;
			font-size: 26rpx;
		}
		/* .waiting_btn{
			background-color: #ff9800;
		}
		.success_btn{
			background-color: #2e7d32;
		}
		.disagree_btn{
			background-color: #f62121;
		} */
	}

	.bonus_table{
	 	background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
		.row{
			display: flex;
			min-height: 120rpx;
			justify-content: space-between;
 		  border-bottom: 2rpx solid #444343;
			&:last-child {
				border-bottom: none;
			}
			.col{
				box-sizing: border-box;
				padding: 30rpx 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				text{
					white-space: normal;
					word-break: break-all;
					font-size: 28rpx;
					text-align: center;
					color: #333;
				}
				.active_num{
					font-size: 30rpx;
					font-weight: bold;
					color: #2e7d32;
				}
				.active_box{
					font-size: 30rpx;
					font-weight: bold;
					background-color: #2e7d32;
					color: #fff;
					display: inline-block;
					padding: 10rpx 18rpx;
					border-radius: 8rpx;
				}
				.chart{
					margin-left: 8rpx;
				}
				.red_char{
					color: red;
				}
				.info_char{
					color: #8f928f;
				}
				.green_char{
					color: #008020;
				}
			}
			.left_col{
				width: 35%;
				background-color: #d7d7d7;
			}
			.right_col{
				width: 65%;
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 6rpx;
				justify-content: center;
				background-color: #f2f2f2;
			}
		}
	}
}
.chat_section {
  margin-top: 40rpx;
  padding: 0 20rpx;
	.chat_item {
		display: flex;
		margin-bottom: 50rpx;
	}
}
.avatar_box{
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}
	.avatar_name{
		display: block;
		width: 80rpx;
		height: 80rpx;
		background-color: #ccc;
		border-radius: 50%;
		text-align: center;
		line-height: 80rpx;
		font-weight: bold;
		font-size: 32rpx;
		color: #fff;
		margin-right: 20rpx;
	}
}

.message_box {
  flex: 1;
	.message_header {
		background-color: #eee;
		padding: 16rpx 40rpx;
		border-top-left-radius: 8rpx;
		border-top-right-radius: 8rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		gap: 30rpx;
		font-size: 24rpx;
		color: #555;
		.message_name{
			font-size: 36rpx;
		}
	}

	.message-content {
		background-color: #fff;
		padding: 20rpx;
		min-height: 60rpx;
		border-bottom-left-radius: 8rpx;
		border-bottom-right-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
		border: 1rpx solid #e5e5e5;
		border-top: none;
	}
	.down_btn_box{
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #169bd5;
		text-decoration: underline;
		text-align: right;
	}
}



.chat-footer {
  display: flex;
  justify-content: space-around;
  margin-top: 60rpx;
  gap: 20rpx;
}

.chat-footer .btn {
  width: 260rpx;
  padding: 0rpx 30rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
}

.confirm-btn {
  background-color: #169bd5;
  color: #fff;
}

.status_pending {
	background-color: #f9ba23;
}
.status_ceo {
  background-color: #33cc33;
}
.status_hr {
  background-color: #3bb3ef;
}
.status_sales {
  background-color: #ff9900;
}
.status_manager {
  background-color: #9966cc;
}
.status_danger {
  background-color: #f92a23;
}
</style>
